require"base.const"
class = require"base/class"
tiny = require"library/tiny-ecs"
love.graphics.setDefaultFilter('nearest', 'nearest')

local callback = require"module/callback/callback"

box_core = {
    world = nil;
    callback = nil;
    entitys = {},
    components = {},
    systems = {},
    utils = {},
    assets = require"module.assets.assets",
    shared = {};
}

local function get_all_luafile_path(dir,tb)
    tb = tb or {}
    local fitem = love.filesystem.getDirectoryItems(dir)
    for k,name in ipairs(fitem) do
        local p = dir.."/"..name
        local type =  love.filesystem.getInfo(p).type

        local fname = name:match("(.+)%.lua")
        if fname then
            table.insert(tb,dir.."/"..fname)
        end

        if type == "directory" then
            get_all_luafile_path(p,tb)
        end
    end
    return tb
end

function box_core:init_core()
    box_core.callback = callback()
    self.assets.load_all()
    self.world = tiny.world()

    for i,path in ipairs(get_all_luafile_path("ecs/shared")) do
        require(path)
    end

    for i,path in ipairs(get_all_luafile_path("ecs/utils")) do
        require(path)
    end

    for i,path in ipairs(get_all_luafile_path("ecs/component")) do
        require(path)
    end
    
    for i,path in ipairs(get_all_luafile_path("ecs/entity")) do
        require(path)
    end

    for i,path in ipairs(get_all_luafile_path("ecs/system")) do
        require(path)
    end
end

function box_core.set_shared(name,data)
    box_core.shared[name] = data
end

function box_core.get_shared(name)
    return box_core.shared[name]
end

function box_core.has_shared(name)
    return box_core.shared[name] ~= nil
end

function box_core.set_utils(name,data)
    box_core.utils[name] = data
end

function box_core.get_utils(name)
    return box_core.utils[name]
end

function box_core.has_utils(name)
    return box_core.utils[name] ~= nil
end

function box_core.call_utils(name,func,...)
    local utils = box_core.utils[name]
    if utils then
        return utils[func](...)
    end
    return nil
end

function box_core.citem(name,value)
    return {name,value}
end

function box_core:create_entity(name,value_table)
    local entity = self.entitys[name]
    if entity then
        return entity:create(value_table)
    end
end

function box_core:get_component(name)
    return self.components[name]
end

function box_core:get_system(name)
    return self.systems[name]
end

function love.update(dt)
    box_core.world:update(dt)
end

return box_core;
